<script>
import request from "../../utils/Request.js";
import { ElMessage } from "element-plus";
import "@wangeditor/editor/dist/css/style.css";
import { Editor } from "@wangeditor/editor-for-vue";

export default {
  name: "RtfView",
  props: {
    id: String,
    rtfText: String,
  },
  components: { Editor },
  watch: {
    id(oV, nV) {
      if (oV !== nV) {
        this.getContent();
      }
    },
  },

  setup() {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();

    // 内容 HTML
    const valueHtml = ref("");

    const editorConfig = {
      placeholder: "",
      readOnly: true,
    };

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    return {
      editorRef,
      valueHtml,
      mode: "default", // 或 'simple'
      editorConfig,
      handleCreated,
    };
  },

  methods: {
    getContent() {
      request({
        url: "/api/project/rtf/content",
        method: "post",
        data: {
          projectId: this.$route.params.projectId,
          id: this.id,
        },
      }).then(({ data }) => {
        if (data.code === 0) {
          this.valueHtml = data.data == null ? "" : data.data;
        } else {
          ElMessage.error(data.msg);
        }
      });
    },
  },

  created() {
    if (this.rtfText != null) {
      this.valueHtml = this.rtfText;
    } else {
      this.getContent();
    }
  },
};
</script>

<template>
  <el-row>
    <Editor
      style="height: 100%; width: 100%; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </el-row>
</template>

<style scoped>
</style>